﻿var drawingManager;
var selectedShape;
var _mapPoints = {};

function initialize() {

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 13,
        center: new google.maps.LatLng(-34.603329384246706, -58.3819270133972),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoomControl: true
    });

    var polyOptions = { strokeWeight: 0, fillOpacity: 0.45, editable: true };

    drawingManager = new google.maps.drawing.DrawingManager({
        drawingControlOptions: {
            drawingModes: [google.maps.drawing.OverlayType.POLYLINE, google.maps.drawing.OverlayType.POLYGON]//MARKER -POLYGON
        },
        markerOptions: { draggable: true },
        polylineOptions: { editable: true, strokeColor: '#5555ff' },
        rectangleOptions: polyOptions,
        circleOptions: polyOptions,
        polygonOptions: polyOptions,
        map: map
    });

    google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
        if (e.type != google.maps.drawing.OverlayType.MARKER) {
            // Switch back to non-drawing mode after drawing a shape.
            drawingManager.setDrawingMode(null);

            // Add an event listener that selects the newly-drawn shape when the user
            // mouses down on it.
            var newShape = e.overlay;
            newShape.type = e.type;
            google.maps.event.addListener(newShape, 'click', function () { setSelection(newShape); });
            setSelection(newShape);
        }
    });

    // Clear the current selection when the drawing mode is changed, or when the map is clicked.
    google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
    google.maps.event.addListener(map, 'click', clearSelection);
    google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
}

function clearSelection() {

    if (selectedShape) {
        selectedShape.setEditable(false);
        selectedShape = null;
        document.getElementById('delete-button').style.visibility = 'hidden';
    }
}

function setSelection(shape) {

    clearSelection();
    selectedShape = shape;
    shape.setEditable(true);

    var deleteControl = document.getElementById('delete-button');
    deleteControl.style.visibility = 'visible';

    //    selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}

function deleteSelectedShape() {
    if (selectedShape) { selectedShape.setMap(null); }
    document.getElementById('delete-button').style.visibility = 'hidden';
}

google.maps.event.addDomListener(window, 'load', initialize);

